﻿'use strict';

/* App Module */


var app = angular.module('saftalk', []);

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  $routeProvider.
        when('/main', {templateUrl: 'content/html/main.html',controller: MainCtrl }).
        when('/register', { templateUrl: 'content/html/registration.html', controller: RegisterCtrl }).
        when('/senior', { templateUrl: 'content/html/senior.html'}).
        when('/family', { templateUrl: 'content/html/family.html'}).
        when('/login', {templateUrl: 'content/html/login.html', controller:LoginCtrl}).
	    when('/login/:qFamilyName/:qPassword/:qChatMode', {templateUrl: 'content/html/login.html', controller:LoginCtrl}).
        otherwise({redirectTo: '/main'});
});


app.factory('applyPubNubChat', function($rootScope,$http, $timeout, $location) {
    var msgs = [];
    return function($scope) {
			
			
		var chatScroll= $('#scrollChat').tinyscrollbar({ sizethumb: 25,wheel:60,lockscroll:true});
		var scrollUpdateFlg=false;
		
		if (chatScroll.length>0) {
			scrollUpdateFlg=true;
		}
		
        if (globalAppParams.userId == 0){
            $location.path('/main');
        }

            $scope.message = Object();
			$scope.messages = [];
            $scope.onlineUsers = new UserListObject();
            $scope.userManagement = new UserManagementListObject();
            $scope.seniorUser = new UserObject("",0,"none",false);
			$scope.realtimeStatus = "Connecting...";
			$scope.channel = globalAppParams.channel;
			$scope.nickname = globalAppParams.name ;
            $scope.userId = globalAppParams.userId;
            $scope.photoId = globalAppParams.photoId;
            $scope.isAdmin = globalAppParams.isAdmin;
		    $scope.fontSize = globalAppParams.fontSize;
			$scope.keyboard = globalAppParams.keyboard;
            $scope.limit = 20;
            $scope.showMessageForm = true;

            
			$scope.isMessage = function(message) {
				return (message.type == "message" || (message.type == "survey" && (message.survey.status != "new" || $scope.chatMode==1)) || message.type == "image");
			};

            $scope.userListFilter = function(user){
                return (user.userId != $scope.userId && user.userId != $scope.seniorUser.userId);
            }
			
			function isUsersListEmpty(){
			}
			
			
			function getPopUpOpacity(){
				if ($scope.chatMode==2)
				{
					return 1;
				} else{
				return 0.7;
				}
			}

			function preload(arrayOfImages) {
			    $(arrayOfImages).each(function () {
			        $('<img/>')[0].src = this;
			    });
			}

			preload([
                '/content/img/survey_hover.png',
                '/content/img/camera_hover.png',
                '/content/img/call_hover.png'
			]);
			
		var onlineUsersTimeOut;
		
		  $scope.getImageUrl = function(photoId)
        {
            if (photoId ==null || photoId == "null" || photoId == "none" || photoId =="")
            {
                return "content/img/img_profile_placeholder.png";
            }
            return "/image/serve?key="+ photoId;
        }
		
		//var ONLINE_TIME_OUT=120000;
		
	
		var disconnectedCounter = 0 ;
		var showDisconnectAlert = function() {
			if ($scope.chatMode==2){
				disconnectedCounter++;
				if (disconnectedCounter>1) {
				$('#disconnectModal').bPopup({
								modalClose: false,
								opacity:1,
								modalColor:'rgb(168, 3, 3)'
							});
				}
			}
		}
		
		var hideDisconnectAlert = function (){
			if ($scope.chatMode==2){
				
				if (disconnectedCounter>0) {
					disconnectedCounter=0;
					$('#disconnectModal').bPopup().close();
				}
			}
		}
		
		$scope.isOnlineUsersFull = function(){
			var ret=false;
			
			for (var user in $scope.onlineUsers.users){
	
				if (!ret){
					ret=$scope.userListFilter($scope.onlineUsers.users[user]);
				}
			}
			return ret;
		}
		
        $scope.getOnlineUsers = function()
        {
            $http({method: 'GET', url: '/presence'}).  success(function(data) {
				hideDisconnectAlert();
                if (!data.success)
                {
                    return;
                }
                else
                {
                	for ( var x in $scope.onlineUsers.users) {
                		var found = false;
                		data.results.forEach(function(result) {
                			if (result.userId == $scope.onlineUsers.users[x].userId ) {
                				found = true;
                			}
                		});
                		if (!found) {
                			$scope.onlineUsers.users.splice(x,1);
                		}
                	}
                	
                    data.results.forEach(function(result){
                        if (result.isSenior)
                        {
                            if ($scope.seniorUser.userId == 0)
                            {
                                $scope.seniorUser = new UserObject(result.name, result.userId, result.photoId, result.isOnline);
                            }
                            else
                            {
                                if (result.isOnline != $scope.seniorUser.isOnline)
                                {
                                    $scope.seniorUser.isOnline = result.isOnline;
                                }
                                
                                if (result.photoId != $scope.seniorUser.photoId) {
                                	
                                	$scope.seniorUser.photoId = result.photoId;
                                }
                            }
                        }
                        var user = $scope.onlineUsers.getUser(result.userId);
                        if (user == null){
                            $scope.onlineUsers.users.push(new UserObject(result.name, result.userId, result.photoId, result.isOnline));
                        }
                        else
                        {
                            if (result.userId == user.userId)
                            {
                                if (result.isOnline != user.isOnline)
                                {
                                    user.isOnline = result.isOnline;
                                }
                                if (result.photoId != user.photoId)
                                {
                                    user.photoId = result.photoId;
                                }
                            }
                        }
                    });
                }
				
				
				
            }).error(function(){
				showDisconnectAlert();
				
			});
            
			
			onlineUsersTimeOut = $timeout(function()		
				{$scope.getOnlineUsers()} ,5000);
        }
		

	
		
		$scope.getOnlineUsers();


			var ctrl_pubnub = PUBNUB.init({
			publish_key   : "pub-8e474368-7add-4283-9b87-caf9efbcdedc",
			subscribe_key : "sub-1ffec1f3-9463-11e1-9376-77819258e702",
			ssl           : false,
			origin        : "pubsub.pubnub.com"
			})
			
			
			function displayMessageSurvey(message){
				
			};
			
			
			ctrl_pubnub.subscribe({
			channel: $scope.channel,
			restore: false,

			callback: function (message) {

				
				if ($scope.chatMode==2){
					//מעביר אותנו חזרה לטאב ההודעות
					$scope.selectMsgsPane();
				}
				$scope.$apply(function () {
					$scope.messages.push(message);
				});
				reduceMessagesNumber();
				if (message.type == "message" && $scope.chatMode==2){
					playSound('Msg');
				}
				
				if (message.type == "survey" && message.survey.status=='new' )
				{	
					if  ($scope.chatMode==2){
						playSound('Survey');
					}
					$scope.popUpMessageSurvey(message);
				}
				if (message.type == 'image') {
					console.log("new image msg! " + message.image);
				}
				
				if (message.type == "videoChat")
				{	console.log("new Video Chat msg");
					console.log(message);
					$scope.handleVideoChatMessage(message,false);
				}
				
				updateChatScroll();
				
				$timeout(function(){
					$('.history > div .image-message img').load(function(){
					reduceMessagesNumber();
					updateChatScroll();
					}
					);
				},100);
				
			},

			disconnect: function () {
				$scope.$apply(function () {
				
				});
			},

			reconnect: function () {
				$scope.$apply(function () {
					
				});
			},

			connect: function () {
				$scope.$apply(function () {
				
					$scope.history();
				});

			}
		});
		
		

		
		$scope.popUpMessageSurvey = function(message) {
					$scope.$apply(function(){
						console.log("Survey received!!!");
						
						$scope.surveyMessage = message;
						console.log("surveyMessage")
						console.log($scope.surveyMessage);
						
						if ($scope.chatMode==2) {
						$scope.popup = $('#surveyMessage').bPopup({
							modalClose: false,
							opacity: getPopUpOpacity()
						});
						
						} else {
							//here will be the code to block users from writing is family mode
						}
						

					})
		}

      
		
		function playSound(soundId,stopFlg) {
			console.log("play soundId"+soundId);
			if (stopFlg) {
				$("#notificationSounds"+soundId).trigger("pause");
			} else {
				$("#notificationSounds"+soundId).trigger("load");
				$("#notificationSounds"+soundId).trigger("play");
			}
		}
		
		$scope.handleVideoChatMessage = function(message,callerFlg) {
			if ( message.videoChat.status=='new') {
				if (message.videoChat.recipientId==globalAppParams.userId || callerFlg){
					$scope.currentVideoChat=message.videoChat;
					console.log("scope video chat is now:")
					console.log($scope.currentVideoChat)
					$rootScope.$broadcast('initVideoChat',{
															sessionId:message.videoChat.sessionId,
															token:message.videoChat.token,
															recipientName:message.videoChat.recipientName,
															callerName:message.videoChat.callerName,
															callerFlg:callerFlg});
			if (callerFlg){
				playSound('Dial');
			} else {
				playSound('Call');
			}
				}
			} else if (message.videoChat.status=="connect" && message.videoChat.callerId==globalAppParams.userId) {
				$rootScope.$broadcast('connectVideoChat');
			} else if (message.videoChat.status=="disconnect" && (message.videoChat.callerId==globalAppParams.userId ||  message.videoChat.recipientId==globalAppParams.userId)) {
				$rootScope.$broadcast('disconnectVideoChat');
			}
					
		}
		
			$scope.videoChatPopup=null
			$scope.$on('videoChatPopupOpen', function(event) {
						console.log('videoChatPopupOpen');
						if ($scope.videoChatPopup==null){
						$scope.videoChatPopup = $('#chatPopUp').bPopup({
						modalClose: false,
						escClose : false,
						opacity: getPopUpOpacity(),
						follow: [false, false],
						zIndex: 2000,
						scrollBar: false,
						  onClose: function() {
										$('#chatPopUp').css({
										width: "",
										height: "",
										top: "",
										left: ""
									  });
							}
					});
					}
			});
			
	
		
			$scope.$on('videoChatPopupClose', function(event,argsObj) {
						
						console.log('videoChatPopupClose');
						console.log($scope.videoChatPopup);
						if ($scope.videoChatPopup){
							$scope.videoChatPopup.close();
							$scope.videoChatPopup=null;
						}
						$scope.currentVideoChat=null;
			});
			
			$scope.currentVideoChat=null;	
		$scope.$on('videoChatStopSounds',function(){
				playSound('Dial',true);
				playSound('Call',true);
		})
		$scope.$on('videoChatChangeStatus', function(videoChatAnswerCall,connectFlg) {
					
						console.log('videoChatChangeStatus'+connectFlg);
						if ($scope.currentVideoChat){
							var videoChat = jQuery.extend({}, $scope.currentVideoChat)
							var status='disconnect';
							if (connectFlg)
							{
								status='connect'
							}
							 else {
								$scope.currentVideoChat=null;
							 }
							 
							
							videoChat.status = status;
						
							var tmpMsg = new PubNubMsgObject($scope.nickname, $scope.userId, $scope.photoId, "videoChat",currentTime(),'videoChatTextFill',null,videoChat);
							
							sendPubNubMessage($scope.channel,tmpMsg);
							
						}	
			});
	

		$scope.publish = function () {

	    if ($scope.message.text == '') {
	    	console.log('Trying to send empty message');
	    	return;
	    }		
		var tmpMsg =  new PubNubMsgObject($scope.nickname,$scope.userId, $scope.photoId, "message",currentTime(),$scope.message.text,null);
	
		
       	sendPubNubMessage($scope.channel,tmpMsg);
			
        //reset the message text
        $scope.message.text = "";
        $("#chat-input").focus();

    };
		
		// survey functions begin here
			
		function SurveyObject(username, question,answers,answerid,status){
			//status - new, close, answer
			this.username=username;
			this.question=question;
			this.answers=answers;
			this.answerid=answerid;
			this.status=status;
		}
		
		$scope.initSurvey = function(){
			$scope.survey = new SurveyObject();
			$scope.survey.answers = []; //'בוקר', 'צהריים', 'ערב'
		}
		$scope.initSurvey();
		$scope.addSurveyAnswer=function(){
			
			if ($scope.newSurveyAnsewr && $scope.newSurveyAnsewr!=''){
				$scope.survey.answers.push($scope.newSurveyAnsewr);
			}
			$scope.newSurveyAnsewr='';
		}
	    $scope.removeSurveyAnswer = function( answerIndex ) {
			$scope.survey.answers.splice(answerIndex, 1);
		 };
		
		
		
		$scope.sendSurvey = function () {

            //toggle the progress bar
            $('#progress_bar').slideToggle();
            console.log("survey was called, question is:" );
            console.log($scope.survey.question);
            if (typeof ($scope.survey.question) == 'undefined' || $scope.survey.question == '') {
            	console.log('Tried to send survey with empty question');
            	return;
            }
            if ( $scope.survey.answers.length == 0) {
            	console.log('Tried to send survey with no answers');
            	return;
            }
            
            var survey = new SurveyObject($scope.nickname, $scope.survey.question,$scope.survey.answers,0,'new');
            var tmpMsg = new PubNubMsgObject($scope.nickname, $scope.userId, $scope.photoId, "survey",currentTime(),'surveyTextFill',survey);
            sendPubNubMessage($scope.channel,tmpMsg);
            $scope.flip('sendMessage');
            //reset the message text
            $scope.initSurvey();
            $("#chat-input").focus();

            $scope.showSurveyForm = false;
            $scope.showMessageForm = true;
        };
		
		function sendPubNubMessage(channel,message){
				ctrl_pubnub.publish({
					channel: channel,
					message: message
				}
			)};
		
		function checkIfSurveyIsActive(messages){
		var popUpFlg=false;
		var finalSurveyMessage=null;
		var message=null;
		
		for (var messageIndex in messages){
				
				message=messages[messageIndex];
			
			if (message.type == "survey" && message.survey.status=='new')
			{	
				finalSurveyMessage=message;
				popUpFlg=true;
			} else if (message.type == "survey" && message.survey.status!='new') {
					finalSurveyMessage=null;
					popUpFlg=false;
			}
		}
		if (popUpFlg) {
			$scope.popUpMessageSurvey(finalSurveyMessage);
		}
	}	
	
		$scope.replySurvey = function (answerId) {
	
		var survey = jQuery.extend({}, $scope.surveyMessage.survey)
		survey.status = "answer";
		survey.answerid=answerId;
		
		var tmpMsg = new PubNubMsgObject($scope.nickname,$scope.userId, $scope.photoId, "survey",currentTime(),'surveyTextFill',survey);
		console.log(tmpMsg);
		sendPubNubMessage($scope.channel,tmpMsg);
			

			//reset the message text
			$scope.message.text = "";
			$scope.popup.close();
		};
		
		// IMAGE SECTION BEGINS HERE
		
		$('#image-upload-file').change(function(event) {
			$('#image-upload-file-text').text($(this).val()).removeClass('placeholder');
		});
		$scope.initImageForm = function () {
			
			$scope.flip('sendImage');
		    $scope.showImageForm = true;
		    $scope.showMessageForm = false;
		    $scope.showSurveyForm = false;
        	$('#image-form-submit').one('click', function(event) {
        		event.preventDefault();
        		$(this).attr('disabled', 'disabled').val('שולח...');
        		$.ajax({
        			url: '/image/family/url',
        			dataType: 'json',
        			success: function(data) {
        				$('#image-upload-form').attr('action', data.message );
        				iframeSendImageForm($scope);	            	
        				$('#image-upload-form').submit();
	            	}
	            });
        		return false;
	        });
		}


		$scope.sendImageOver = function (imageUrl, text) {

			//toggle the progress bar
			//$('#progress_bar').slideToggle();
			console.log("Sending image!");
			
			var tmpMsg = new PubNubMsgObject($scope.nickname, $scope.userId, $scope.photoId, "image",currentTime(),text,null,null, imageUrl );
			sendPubNubMessage($scope.channel,tmpMsg);
			
			$scope.flip('sendMessage');
			$scope.showImageForm = false;
			$scope.showSurveyForm = false;
			$scope.showMessageForm = true;
			$('#image-upload-form').get(0).reset();
			$('#image-upload-file-text').text('בחר קובץ...').addClass('placeholder');
			$('#image-form-submit').removeAttr('disabled').val('שלח תמונה»');
			$("#chat-input").focus();
		};
		
		
	
		$scope.popupImage = function(key) {
			$timeout(function(){
			$('#imagePopUp').one('mousedown', function() {
						$('#imagePopUp').bPopup().close();
					})},1000);
					
			$('#imagePopUp').html("<img id='image-popup-img' style='height:100%;max-width:100%' src='/image/serve?key="+ key+"'>");
		
					fitImgToWindow(this);
					$scope.imagePopup = $('#imagePopUp').bPopup({
					modalClose: true,
					opacity: getPopUpOpacity(),
					follow: [false, false],
					position: [0, 0],
					zIndex: 2000,
					scrollBar: false,
					  onClose: function() {
									$('#imagePopUp').css({
									width: "",
									height: "",
									top: "",
									left: ""
								  }).html('');
									
						}
					})
					


		
			
		
		}
		var gallerySlider = null;
		$scope.loadGallery = function () {
			$('#photoGallery').css("opacity",0)
			$('#photoGallery').html('<div class="touchslider touchslider-demo"><div class="touchslider-nav"><a class="touchslider-prev"><span class="touchslider-prev-in"></span><a class="touchslider-next"><span class="touchslider-next-in"></span></a></div><div class="touchslider-viewport"><div style="width:100% !important"></div></div></div>')
			;
			
    		$.ajax({
    			url: '/image/family',
    			dataType: 'json',
    			success: function(data, textStatus, jqXHR) {
					
					
					var width=$('.touchslider-viewport').width();
					var height=Math.round(($(window).height()-100)*0.90);
					$('.touchslider-viewport').height(height);
					
    				var imgData = [];
					if (data.length==0){
					$('#photoGallery').html("<div class='contentArea' style='width:100%;font-size:400%;text-align:center;'><br/>עדיין אין תמונות בגלריה<br/><br/></div></div>")
					};
					for (var i in data) {
						
						//alert (data[i].photoId);
						
						$('#photoGallery .touchslider-viewport > div').append('<div class="touchslider-item "><div class="img-item"><div class="contentArea img"><img src="/image/serve?key=' +data[i].photoId+ '"/></div></div></div>')
						//imgData.push({image: '/image/serve?key=' +data[i].photoId ,
						//			  layer: '<h2 class="gallery-description">'+data[i].description+'</h2>',
						//			  //title: data[i].description,
						//			  thumb: '/image/thumb?key=' +data[i].photoId})
					}
				
					var maxwidth=width-20;
					var maxheight=height-30;
					$(".touchslider .img-item img").css("max-width",maxwidth);
					$(".touchslider .img-item img").css("max-height",maxheight);
					$(".touchslider .img-item img").load(function() {
						$(this).css("height",maxheight);
						
						
					});
					
				
					$(".touchslider .img-item").width(maxwidth+10);
						
					jQuery(function($) {
						gallerySlider=$(".touchslider").touchSlider();
					});
					$timeout(function(){
					$('#photoGallery').animate({
						opacity: 1
					}, 2100);
					},500);
					
					$(".touchslider .touchslider-prev-in").mousedown(function(){$(this).addClass("active");});
					$(".touchslider .touchslider-prev-in").mouseup(function(){var elem=this;	$timeout(function(){$(elem).removeClass("active");},400)});
					$(".touchslider .touchslider-next-in").mousedown(function(){$(this).addClass("active");});
					$(".touchslider .touchslider-next-in").mouseup(function(){var elem=this;	$timeout(function(){$(elem).removeClass("active");},400)});
										
					
    			}
    		});
		}
		
		// IMAGE SECTION ENDS HERE

		
		$scope.sendVideoChat = function (recipientId,recipientName) {
			$rootScope.$broadcast('videoChatPopupOpen');
			$http({method: 'GET', url: '/saftalk/newchat'}).  success(function(data, status, headers, config) {
					
						if (!data.success)
						{
					
								return null;
							
						} else {
							
								var videoChatTokenObj=data
									if (videoChatTokenObj==null){
										return;
									}
									var callerId=globalAppParams.userId;
									var callerName=globalAppParams.name;
									var videoChat = new VideoChatObject(callerId,callerName,recipientId,recipientName,videoChatTokenObj.sessionId,videoChatTokenObj.token,'new')
									console.log
									var tmpMsg = new PubNubMsgObject($scope.nickname, $scope.userId, $scope.photoId, "videoChat",currentTime(),'videoTextFill',null,videoChat);
									$scope.handleVideoChatMessage(tmpMsg,true);
									sendPubNubMessage($scope.channel,tmpMsg);
							
			}}).error(function(){
				
			});

		}
		
	
		
		function PubNubMsgObject(username,userId,photoId,type,time,text,survey,videoChat,image){
			// type - message, survey, videoChat, image
			this.username=username;
			this.type=type;
			this.text=text;
			this.time=time;
            this.userId = userId;
            this.photoId = photoId;
			if (survey) {
				this.survey=survey;
			}
			if (videoChat) {
				this.videoChat=videoChat;
			}
			if (image) {
				this.image=image;
			}
	
		}
		
        function UserObject(userName, userId, photoId, isOnline){
            this.name = userName;
            this.userId = userId;
            this.isOnline = isOnline;
			this.photoId = photoId;

            this.getStatus = function(){
                if (this.isOnline)
                {
                    return "מחובר";
                }
                return "מנותק";
            };

            this.getImageUrl = function()
            {
                return $scope.getImageUrl(this.photoId);
            };

            this.getStatusCircle = function()
            {
                if (this.isOnline)
                {
                    return "content/img/circle_green.png";
                }
                else
                {
                    return "content/img/circle_red.png";
                }
            };
        };

        function UserListObject(){
            this.users = [];
            this.getUser = function (userId)
            {
                for (var x in this.users)
                {
                    if (this.users[x].userId == userId)
                    {
                        return this.users[x];
                    }
                }
                return null;
            };
        };
	

			
		var updateChatScroll= function (){
			if (scrollUpdateFlg){
				$timeout(function(){chatScroll.tinyscrollbar_update('bottom');},1);
				$timeout(function(){chatScroll.tinyscrollbar_update('bottom');},200); 
				$timeout(function(){chatScroll.tinyscrollbar_update('bottom');},2000);
				$timeout(function(){chatScroll.tinyscrollbar_update('bottom');},3000);
			}
		}
		
		$scope.history = function () {
			ctrl_pubnub.history({
				channel: $scope.channel,
				limit: $scope.limit
			}, function (messages) {

				$scope.$apply(function () {
					$scope.messages = messages[0];
				});
				reduceMessagesNumber();
				$timeout(reduceMessagesNumber,500);
				$timeout(function(){
					$('.history > div .image-message img').load(function(){
					reduceMessagesNumber();
					updateChatScroll();
					});
				},1000);
				checkIfSurveyIsActive(messages[0]);
				
				updateChatScroll();
				});
			};
		
	

		function VideoChatObject(callerId,callerName,recipientId,recipientName,sessionId,token,status){
				// status - new,disconnect,connect
				this.callerId = callerId;
				this.callerName = callerName;
				this.recipientId = recipientId;
				this.recipientName = recipientName;
				this.sessionId = sessionId;
				this.token = token;
				this.status = status;
		}

        $scope.timeFormatter = function (string){
            var ret="";
            if (string){
                var resultArray = string.split(":");
                ret=resultArray[0]+":"+resultArray[1];
            }
            return ret;
        }
		
		$scope.currentMsgFrom="sendMessage";
		
		$scope.flip = function(className){
			console.log("flip"+className);
			$scope.currentMsgFrom=className;
			var background=$("#flipbox").css("background-color");
			$("#flipbox").flip({
					direction:"tb",
					color: background,
					speed: 200
				});
		}
		
		function UserManagementObject(name, email, userId, photoId, phoneNumber, generatedPass) {
            this.name = name;
            this.email = email;
            this.userId = userId;
            this.photoId = photoId;
            this.phoneNumber = phoneNumber;
            this.generatedPassword = generatedPass;
            
            this.getImageUrl = function()
            {
                return $scope.getImageUrl(this.photoId);
            };
		}
		
        function UserManagementListObject(){
        	this.adminUser;
        	this.seniorUser;
        	
            this.users = [];
            this.getUser = function (userId)
            {
                for (var x in this.users)
                {
                    if (this.users[x].userId == userId)
                    {
                        return this.users[x];
                    }
                }
                return null;
            };
            
            this.putUser = function (user, isAdmin, isSenior) {
            	
            	if (isAdmin) {
            		this.adminUser = user;
            	} else if (isSenior) {
            		this.seniorUser = user;
            	} else {
                	var existing = this.getUser(user.userId);
                	if (existing == null) {
                		this.users.push(user);
                	} else {
                		for ( var x in this.users) {
                			if (this.users[x].userId == user.userId) {
                				this.users[x] = user;
                			}
                		}
                	}            		
            	}
            }
            this.removeUser = function(userId) {
                for (var x in this.users)
                {
                    if (this.users[x].userId == userId)
                    {
                        this.users.splice(x,1);
                    }
                }
            }
        };

	 	$scope.popupUserEdit = function(user) {
	 		$scope.userEditPopup = $('#userEditPopUp').bPopup({
				modalClose: true,
				opacity: 0.5,
				follow: [false, false],
				zIndex: 2000,
				scrollBar: false,
				//loadUrl: '/content/html/user.html', //Uses jQuery.load()
				onOpen: function() {
					$rootScope.$broadcast('initUserEdit', {userObj: user} );
				},
				onClose: function() {
					$scope.loadUsers();		
				}
			});
	 	}
	 	$scope.popupUserAdd = function(user) {
	 		$scope.userEditPopup = $('#userEditPopUp').bPopup({
				modalClose: true,
				opacity: 0.5,
				follow: [false, false],
				zIndex: 2000,
				scrollBar: false,
				//loadUrl: '/content/html/user.html', //Uses jQuery.load()
				onOpen: function() {
					$rootScope.$broadcast('initUserAdd', {userObj: user} );
				}
			});
	 	}
	 	
        $scope.$on('finishUserEditOrAdd', function(event,argsObj) {
        	
        	$timeout(function(){
        		$('#userEditPopUp').bPopup().close();
        		//$scope.loadUsers();
        		var user = argsObj.userObj;
        		$scope.userManagement.putUser(new UserManagementObject(user.name, user.email, user.userId, user.photoId, user.phoneNumber, user.generatedPassword), user.isAdmin, user.isSenior);
        	}
        	,4000);	
        });
	 	
        
	 	$scope.popupSeniorSettings = function() {
	 		
	 		$scope.seniorSettingsPopup = $('#seniorSettingsPopUp').bPopup({
				modalClose: true,
				opacity: 0.5,
				follow: [false, false],
				zIndex: 2000,
				scrollBar: false,
				onOpen: function() {
					//$rootScope.$broadcast('initUserEdit', {userObj: user} );
				},
				onClose: function() {
					//$scope.loadUsers();		
				}
			});
	 	}
	 	
		$('#profile-upload-file').change(function(event) {
			$('#profile-upload-file-text').text($(this).val()).removeClass('placeholder');
		});
	 	$scope.popupProfileImageUpload = function(user) {
	 		$('#profile-upload-user').val(user.userId);
	 		$scope.userImageEdit = $('#profileImagePopup').bPopup({
	 			modalClose:true,
	 			opacity: 0.5,
	 			follow: [false, false],
	 			zIndex: 2000,
	 			scrollBar: false,
	 			onOpen: function() {
	 				$('#profile-upload-submit').one('click', function(event) {
	 	        		event.preventDefault();
	 	        		$(this).attr('disabled', 'disabled').val('שולח...');
	 	        		$.ajax({
	 	        			url: '/image/user/url',
	 	        			dataType: 'json',
	 	        			success: function(data) {
	 	        				console.log("Setting form action to be:" + data.message);
	 	        				$('#profile-upload-form').attr('action', data.message );
	 	        				iframeProfileImageForm($scope);	            	
	 	        				$('#profile-upload-form').submit();
	 		            	}
	 		            });
	 	        		return false;
	 		        });	 				
	 			},
	 			onClose: function() {	 				
	 				$('#profile-upload-form').get(0).reset();
	 				$('#profile-upload-submit').removeAttr('disabled').val('שלח»');
	 				$('#profile-upload-file-text').text('בחר קובץ...').addClass('placeholder');
	 				$timeout(function(){ $scope.loadUsers();},2000);
	 			}
	 			
	 		});
	 	}
	 	
		$scope.deleteUser = function(user) {
			
			$http({
				method: 'POST',
				url: '/saftalk/user/remove', 
				data: $.param({userId: user.userId}),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
				}).success(function(data) {
	            if (!data.success) {            	
	            	console.log("Failed to remove user");
	            	console.log(data.message);
	            	$scope.loadUsers();
	                return; 
	            }
	            
	            $scope.userManagement.removeUser(data.userId);
	            //$timeout(function(){ $scope.loadUsers();},2000);
			});
		}
		
		 $scope.loadUsers = function()
	        {
	            $http({method: 'GET', url: '/saftalk/list'}).success(function(data) {
	                if (!data.success) {
	                    return; 
	                }
	                $scope.userManagement.users = [];
	                data.users.forEach(function(user){
	                	$scope.userManagement.putUser(new UserManagementObject(user.name, user.email, user.userId, user.photoId, user.phoneNumber, user.generatedPassword), user.isAdmin, user.isSenior);
	                });
	            });
	        }
		 
		 $scope.popupSeniorInstall = function() {
			 $scope.userImageEdit = $("#seniorKioskModal").bPopup({
		 			modalClose:true,
		 			opacity: 0.5,
		 			follow: [false, false],
		 			zIndex: 2000,
		 			scrollBar: false
			 });
		 }
    };
  });
  
	
	

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

app.directive('fadeEffect', [ '$timeout', function($timeout) {
var def = {
    restrict : 'A', 
	
    link : function(scope, element, attrs) {
	scope.$watch(function(){
	var changeflg
	changeflg=(element[0].style.display!="none")

	return changeflg},function(){
	
	if ($(element).css("display")!="none"){
		$(element).hide();
		if (attrs.fadeEffect=="slideDown") {
		$(element).slideDown();
		} else{
			$(element).fadeIn();
		}
	 } 
	
	},false);

		scope.$watch("chatMode",function(){"changed"});

    }
};
return def;
}])

app.directive('coolFade', function() {
    var def={
        compile: function(elm) {
            //console.log('compiling');
            $(elm).css('opacity', 0);
            return function(scope, elm, attrs) {
             //   console.log('animating');
                $(elm).animate({
                    opacity: 1
                }, 1100);
            };
        }
    };
	return def;
});

app.directive('fitText', function() {
    var def={
       link : function(scope, element, attrs) {
			var scale=1;
			if (attrs.fitText!=""){
				scale=attrs.fitText;
			}
            $(element).fitText(scale);
    }};
	return def;
});

app.directive('tabs', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: false,
      controller: function($scope, $element) {
        var panes = $scope.panes = [];
		
        $scope.selectPane = function(pane) {
          angular.forEach(panes, function(pane) {
            pane.selected = false;
          });
          pane.selected = true;
          
          if (pane.tabid=='pictures') {
        	  $scope.loadGallery();
          }
        }
		
		$scope.selectMsgsPane= function(){
		  $scope.selectPane ($scope.panes[0]);
		};
		
        this.addPane = function(pane) {
          if (panes.length == 0) $scope.selectPane(pane);
          panes.push(pane);
        }
      },
     
	  templateUrl: "seniorTabsTpl.html",	
      replace: true
    };
  }).
  directive('tab', function() {
    return {
      require: '^tabs',
      restrict: 'E',
      transclude: true,
      scope: { tabtitle: '@',isSeniorAlertButton: '@', tabid: '@' },
      link: function(scope, element, attrs, tabsCtrl) {
        tabsCtrl.addPane(scope);
      },
      templateUrl: 'seniorPaneTpl.html',
      replace: true
    };
  })

var globalAppParams = Object();